﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using CarolLib;
using CarolLib.Control;
using Excel;
using MiniCMS.Business;
using MiniCMS.Configuration;
using MiniCMS.Forms;
using MiniCMS.Model;
using System.Data.OleDb;

namespace MiniCMS.UserControls
{
    [ModuleContract("D143FCD2-E070-4F24-93CD-34CF895FAEEB", "查询(&Q)", "查询", (int)(PowerFlagEnmus.客户信息))]
    public partial class UCCustomerList : MdiUserControl
    {
        #region Members

        frmEditSearches searchform;

        #endregion
        
        #region Ctor.

        public UCCustomerList()
            : base()
        {
            InitializeComponent();

            CheckPower(AuthUserContext.Instance.User.PowerFlag);

            dgvCustomerList.AutoGenerateColumns = false;
            foreach (DataGridViewColumn col in dgvCustomerList.Columns)
                col.DataPropertyName = col.HeaderText;

            searchform = new frmEditSearches(UpdateQueryString);
        }

        public UCCustomerList(XmlNode node)
            : this()
        {
            InitializeComponent();
        }

        #endregion

        #region EventHandlers

        private void btnQuickSearch_Click(object sender, EventArgs e)
        {
            string query = string.Format("客户编号 like '%{0}'", this.tbCustomerNo.Text.Trim());
            QueryCustomer(query);
        }

        private void btnSearchC_Click(object sender, EventArgs e)
        {
            searchform.ShowDialog();
        }

        private void btnClearCondition_Click(object sender, EventArgs e)
        {
            this.tbSearchC.Text = string.Empty;
            this.tbCustomerNo.Text = string.Empty;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string query = tbSearchC.Text.Trim();
            QueryCustomer(query);
        }

        private void btnExportData_Click(object sender, EventArgs e)
        {
            ExportExcel(dgvCustomerList);
        }

        private void dgvCustomerList_DoubleClick(object sender, EventArgs e)
        {
            if (this.dgvCustomerList.SelectedRows.Count == 0)
                return;

            double id = Convert.ToDouble(this.dgvCustomerList.SelectedRows[0].Cells[0].Value);

            if (GlobalStatusContext.ShowDetail != null)
            {
                GlobalStatusContext.ShowDetail(id);
                this.MdiCantainer.SelectMdiForm("UCCustomerDetailInfo");
            }
        }

        private void btnImportData_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.DefaultExt = "xls";
            openDialog.Filter = "Excel文件|*.xls";
            if (openDialog.ShowDialog() != DialogResult.OK)
                return;

            try
            {
                var list = OleDbDataProvider.ImportFromExcel(openDialog.FileName);

                int total = list.Count;
                int successCount = 0;
                string success = string.Empty;
                string fail = string.Empty;

                list.ForEach(c =>
                {
                    c.制表人 = AuthUserContext.Instance.User.FullName;
                    c.档案修改时间 = DateTime.Now.ToString();
                    c.复核状态 = "未复核";

                    if (OleDbDataProvider.InsertCustomerInfo(c) == 1)
                    {
                        successCount++;
                        success += c.客户编号 + ",";
                    }
                    else
                        fail += string.Format("{0}({1}),", c.客户编号, c.客户姓名);
                });

                if (fail != string.Empty)
                    MessageBox.Show(string.Format("数据导入完成，共{0}条，其中成功导入{1}条，失败的记录为：\r\n" + fail, total, successCount));
                else
                    MessageBox.Show(string.Format("数据导入完成，共{0}条", total, successCount));

                QueryCustomer("客户编号 in (" + success + "0)");
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入过程中发生错误，请检查您的Excel格式\n错误信息:" + ex.Message);
            }
        }

        private void tbCustomerNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnQuickSearch_Click(sender, e);
            }
        }

        #endregion

        #region Methods

        private void QueryCustomer(string query)
        {
            try
            {
                if (!string.IsNullOrEmpty(query))
                    query = "WHERE " + query;
                dgvCustomerList.DataSource = OleDbDataProvider.QueryCustomerInfoTable(query);
                MessageBox.Show("查询出: "+dgvCustomerList.RowCount+" 条记录！");
                dgvCustomerList.Refresh();
                dgvCustomerList.Update();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询条件有误，错误信息为：\r\n" + ex.Message);
            }
        }

        public void ExportExcel(DataGridView dgv)
        {
            if (dgv == null) 
                return;

            string saveFileName = "";
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "Sheet1";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) 
                return; //被点了取消

            Excel.Application xlApp = new Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Excel");
                return;
            }

            Excel.Workbooks workbooks = xlApp.Workbooks;
            Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
            Excel.Range range;

            string oldCaption = DateTime.Today.ToString("yy-MM-dd");
            long totalCount = dgv.Rows.Count;
            long rowRead = 0;
            float percent = 0;

            worksheet.Cells[1, 1] = DateTime.Today.ToString("yy-MM-dd");
            //写入字段
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                worksheet.Cells[2, i + 1] = dgv.Columns[i].HeaderText;
                range = (Excel.Range)worksheet.Cells[2, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;

            }
            //写入数值

            this.lbl_process.Visible = true;

            for (int r = 0; r < dgv.Rows.Count; r++)
            {
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    worksheet.Cells[r + 3, i + 1] = dgv.Rows[r].Cells[i].Value.ToString();
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
                this.lbl_process.Text = "正在导出数据[" + percent.ToString("0.00") + "%]..."; //这里可以自己做一个label用来显示进度.
                System.Windows.Forms.Application.DoEvents();
            }
            
            this.lbl_process.Visible = false;

            range = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[dgv.Rows.Count + 2, dgv.Columns.Count]);
            range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);

            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
            range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;

            if (dgv.Columns.Count > 1)
            {
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
                range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
            }

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            if (fileSaved && File.Exists(saveFileName))
            {
                //System.Diagnostics.Process.Start(saveFileName);
                MessageBox.Show("导出成功！", "通知");
            }
        }

        public void UpdateQueryString(string query)
        {
            this.tbSearchC.Text = query;
        }

        #endregion
    }
}
